package com.itheima.stock.service.impl;

import com.google.common.base.Strings;
import com.itheima.stock.mapper.SysUserMapper;
import com.itheima.stock.pojo.SysUser;
import com.itheima.stock.service.UserService;
import com.itheima.stock.utils.IdWorker;
import com.itheima.stock.vo.req.LoginReqVo;
import com.itheima.stock.vo.resp.LoginRespVo;
import com.itheima.stock.vo.resp.R;
import com.itheima.stock.vo.resp.ResponseCode;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service("service")
public class UserServiceImpl implements UserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private RedisTemplate template;
    @Autowired
    private IdWorker idWorker;
    @Override
    public R<LoginRespVo> login(LoginReqVo vo) {
        //判断输入参数合法性
        if(vo==null|| Strings.isNullOrEmpty(vo.getUsername())||Strings.isNullOrEmpty(vo.getPassword())||Strings.isNullOrEmpty(vo.getCode())||Strings.isNullOrEmpty(vo.getRkey())){
            //响应请求参数异常
            return R.error(ResponseCode.DATA_ERROR.getMessage());
        }
        //验证码判断：
        String code = (String)template.opsForValue().get("ck:"+vo.getRkey());
        if(code==null){
            return R.error(ResponseCode.SYSTEM_VERIFY_CODE_OVERTIME.getMessage());
        }
        //这里一定要先排除掉code为null的情况，否则会空指针异常
        if(!code.equals(vo.getCode())){
            return R.error(ResponseCode.SYSTEM_VERIFY_CODE_ERROR.getMessage());
        }
        //验证成功后，可以及时把该验证码缓存删除
        template.delete("ck:"+vo.getRkey());
        //根据用户名查询用户信息（包含加密后密文）
        SysUser userInfo = sysUserMapper.findUserByUserName(vo.getUsername());
        //判断对应用户是否存在，以及密码匹配
        if(userInfo==null||! passwordEncoder.matches(vo.getPassword(),userInfo.getPassword())){
            return R.error(ResponseCode.SYSTEM_PASSWORD_ERROR.getMessage());
        }
        //将查询的用户信息封装到LoginRespVo中
        //我们不要把所有数据都返回，按需返回即可，否则既不安全，又浪费资源
        LoginRespVo loginRespVo = new LoginRespVo();
        //把某对象的属性值复制到指定对象中
        BeanUtils.copyProperties(userInfo,loginRespVo);
        //组装并响应到前端
        return R.ok(loginRespVo);
    }

    //验证码生成并保存
    @Override
    public R<Map> generateCode() {
//        char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
//                'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
//                'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
//        Random random = new Random();
//        String captcha="";
//        for (int i = 0; i < 4; i++) {
//            int index = random.nextInt(chars.length);
//            captcha += chars[index];
//        }
//        System.out.println(captcha);

        //用工具类来生成随机code
        String code = RandomStringUtils.randomAlphanumeric(4);
        //将验证码加入缓存,并设置存活时间
        String sessionId= String .valueOf(idWorker.nextId());
        //id加个前缀，方便阅读和维护。存取都要加。
        template.opsForValue().set("ck:"+sessionId,code,300, TimeUnit.SECONDS);
        //将数据包装后响应
//        LoginReqVo loginReqVo = new LoginReqVo();
//        loginReqVo.setCode(code);
//        loginReqVo.setRkey(key);
        Map<String, String > captcha  = new HashMap<>();
        captcha.put("code",code);
        captcha.put("rkey",sessionId);
        System.out.println(captcha);
        return R.ok(captcha);

    }
}
